﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Linq.Expressions;
using System.ComponentModel;
using WebApp.BaseDataSvc;
using YY.Common;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;

namespace WebApp
{
    public class AjaxResult<T>
    {
        public T Data { get; set; }
        public string Msg { get; set; }
    }

    public static class WebCommon
    {
        /// <summary>
        /// 在客户端执行脚本。
        /// </summary>
        /// <param name="msg">>要显示的信息。</param>
        /// <param name="page">所在页面</param>
        public static void CreateJs(string strScript, Page page)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "CreateJs", "<script type=\"text/javascript\">" + strScript + "</script>");
        }

        /// <summary>
        /// 页面通过后台代码加载CSS
        /// </summary>
        /// <param name="page"></param>
        /// <param name="cssPath"></param>
        public static void AddStyleSheet(Page page, string cssPath)
        {
            HtmlLink link = new HtmlLink();
            link.Href = cssPath;
            link.Attributes["rel"] = "stylesheet";
            link.Attributes["type"] = "text/css";
            link.Attributes["href"] = cssPath;
            //head.Controls.Add(link);
            page.Header.Controls.Add(link);
        }

        /// <summary>
        /// 判断验证码是否正确
        /// </summary>
        /// <param name="code">用户输入的验证码</param>
        /// <param name="page">所在页面</param>
        /// <returns>返回验证码是否正确</returns>
        public static bool CheckValidateCode(string code, Page page)
        {
            try
            {
                if (code.ToUpper() != page.Session["rc_validate_code"].ToString().ToUpper()) return false;
                return true;
            }
            catch (Exception e)
            {
                e.ToString();
                return false;
            }
        }

        /// <summary>
        /// 检测用户对页面的指定操作是否有权
        /// </summary>
        /// <param name="uId"></param>
        /// <param name="mId"></param>
        /// <param name="opFlag"></param>
        /// <returns></returns>
        //public static bool CheckPermit(int uId, int mId, GDR.Model.EnumType.PermitType opFlag)
        //{ //return new GDR.BLL.Permission().AccessPermit(uId, mId, opFlag); 
        //    return false;
        //}

        public static void CheckLogin(BasePage page, int MId)
        {
            if (page.Session["User"] == null)
            {
                page.RegisterStartupScript("alert", "<script type=\"text/javascript\">alert('由于您未登录系统或超时，请重新登录');parent.window.location='login.aspx'</script>");
            }
            else
            {
                if (page.UserPermitDatas != null & page.ModuleId > 0)
                {
                    bool pass = page.UserPermitDatas.Any(p => p.moduleId == page.ModuleId);
                    if (!pass)
                    {
                        page.Response.Write("<br/><br/><center><span color=\"red\">您还没有访问该页面的权限，请切换用户登录或与管理员联系</span></center>");
                        page.Response.End();
                    }
                }
            }
        }
        /// <summary>
        /// 转换分页后的datatable
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static DataTable GetPagedTable(DataTable dt, int pageIndex, int pageSize)
        {

            if (pageIndex == 0)
                return dt;
            DataTable newDt = dt.Clone();
            //newdt.Clear();
            int rowBegin = (pageIndex - 1) * pageSize;
            int rowEnd = pageIndex * pageSize;

            if (rowBegin >= dt.Rows.Count)
                return newDt;

            if (rowEnd > dt.Rows.Count)
                rowEnd = dt.Rows.Count;

            for (int i = rowBegin; i <= rowEnd - 1; i++)
            {
                DataRow newDr = newDt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newDr[column.ColumnName] = dr[column.ColumnName];
                }
                newDt.Rows.Add(newDr);
            }
            return newDt;
        }

        /// <summary>
        /// 在客户端显示弹出对话框。
        /// </summary>
        /// <param name="msg">>要显示的信息。</param>
        /// <param name="page">所在页面</param>
        public static void Alert(string msg, Page page)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "alert", "<script language=\"javascript\">alert('" + msg + "');</script>");
        }

        /// <summary>
        /// Select绑定XML数据
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="select"></param>
        /// <param name="selectedValue"></param>
        public static void BindSelectFromXML(string xmlPath, HtmlSelect select, string selectedValue)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath(xmlPath));
            DataView dv = new DataView(ds.Tables[0]);
            foreach (DataRowView row in dv)
            {
                ListItem li = new ListItem(row["Name"].ToString(), row["Value"].ToString());
                select.Items.Add(li);
                if (selectedValue == row["Value"].ToString())
                    li.Selected = true;
            }
        }

        /// <summary>
        /// 获取XML返回ListItem序列
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        public static List<ListItem> GetListByXML(string xmlPath)
        {
            List<ListItem> list = new List<ListItem>();
            DataSet ds = new DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath(xmlPath));
            DataView dv = new DataView(ds.Tables[0]);
            foreach (DataRowView row in dv)
            {
                ListItem li = new ListItem(row["Name"].ToString(), row["Value"].ToString());
                list.Add(li);
            }
            return list;
        }

        public static DataTable GetDataTableByXML(string xmlPath)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath(xmlPath));
            if (ds != null)
                return ds.Tables[0];
            return null;
        }

        /// <summary>
        /// 获取XML数据中指定值对应的名称
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetNameByXML(string xmlPath, string value)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath(xmlPath));
            DataView dv = new DataView(ds.Tables[0]);
            foreach (DataRowView row in dv)
            {
                if (value == row["Value"].ToString())
                    return row["Name"].ToString();
            }
            return string.Empty;
        }


        public static string GetFileHtml(string fileName, Encoding code)
        {
            try
            {
                using (StreamReader sr = new StreamReader(fileName, code))
                {
                    return sr.ReadToEnd();
                }
            }
            catch
            { }
            return string.Empty;
        }

        public static string GetHostUrl()
        {
            string vPath = HttpContext.Current.Request.ApplicationPath;
            if (vPath == "/")
            {
                vPath = string.Empty;
            }
            string Port = ":" + HttpContext.Current.Request.Url.Port.ToString();
            if (Port == ":80")
            {
                Port = string.Empty;
            }
            return "http://" + HttpContext.Current.Request.Url.Host + Port + vPath + "/";
        }

        public static string GetAttachRoot()
        {
            return WebCommon.GetHostUrl() + "ybyupload/uploadfiles/";
        }

        public static string GetContentType(string ext)
        {

            string contentType = "application/octetstream";

            //string ext = System.IO.Path.GetExtension(fileName).ToLower();

            Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

            if (registryKey != null && registryKey.GetValue("Content Type") != null)

                contentType = registryKey.GetValue("Content Type").ToString();

            return contentType;

        }

        public static string GetIdFileName(string filePath)
        {
            try
            {
                string strHead = DateTime.Now.ToString("yyyyMMddhhmmssffff");
                return Path.GetDirectoryName(filePath) + @"\" + Path.GetFileNameWithoutExtension(filePath) + "_" + strHead + Path.GetExtension(filePath);
            }
            catch { }
            return filePath;
        }

        /// <summary>
        /// Ensures that a filename is unique by appending [x] to the filename if it alredy exists
        /// </summary>
        /// <param name="filePathAndName">The file with path to check </param>
        /// <returns></returns>
        public static string GetUniqueFileName(string filePath)
        {
            string newFilename = string.Empty;

            //check if file exists 
            if (File.Exists(filePath))
            {
                string path = Path.GetDirectoryName(filePath);
                string ext = Path.GetExtension(filePath);
                string fname = Path.GetFileNameWithoutExtension(filePath);

                int nr = 1;
                if (fname.EndsWith("]"))
                {
                    if (int.TryParse(fname.Substring(fname.LastIndexOf("[") + 1, 1), out nr))
                    {
                        nr++;
                    }
                }
                int startIndex = fname.IndexOf("[");
                int endIndex = fname.IndexOf("]");
                if (startIndex != -1 && endIndex != -1)
                    fname = fname.Remove(startIndex);
                newFilename = Path.Combine(path, fname + "[" + nr + "]" + ext);

                return GetUniqueFileName(newFilename);
            }
            return filePath;
        }

        /// <summary>
        /// DataTable分页实现
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <returns>返回已分页的DataTable</returns>
        public static DataTable GetPagingTable(DataTable dt, int pageIndex, int pageSize)
        {

            if (pageIndex == 0)
                return dt;
            DataTable newDt = dt.Clone();
            //newdt.Clear();
            int rowBegin = (pageIndex - 1) * pageSize;
            int rowEnd = pageIndex * pageSize;

            if (rowBegin >= dt.Rows.Count)
                return newDt;

            if (rowEnd > dt.Rows.Count)
                rowEnd = dt.Rows.Count;

            for (int i = rowBegin; i <= rowEnd - 1; i++)
            {
                DataRow newDr = newDt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newDr[column.ColumnName] = dr[column.ColumnName];
                }
                newDt.Rows.Add(newDr);
            }
            return newDt;
        }

        public static string GetMoneyVal(object input)
        {
            try
            {
                if (input != null)
                {
                    string rtn = string.Format("{0:C2}", input);
                    return rtn.Replace("￥", "");
                }
            }
            catch { }
            return string.Empty;
        }

        /// <summary>
        /// 操作是否合法
        /// </summary>
        ///  <param name="page">当前页面</param>
        /// <param name="opKey">操作关键字</param>
        /// <returns></returns>
        public static bool IsActionPermit(BasePage page, EnumCommon.PermissionOpType opType)
        {

            if (page.Session["User"] != null)
            {
                if ((page.Session["User"] as TB_User).role.Equals((int)EnumCommon.SysRoleType.管理员))//管理员不受限制
                    return true;
                try
                {
                    if (page.UserPermitDatas != null)
                    { return page.UserPermitDatas.Any(p => p.opKey == Enum.GetName(typeof(EnumCommon.PermissionOpType), opType)); }
                }
                catch { }
            }
            return false;
        }

        /// <summary>
        /// 返回上传文件服务器目录
        /// </summary>
        /// <param name="date">文件上传日期</param>
        /// <returns>文件所在目录</returns>
        public static string GetUploadFileDir(DateTime date)
        {
            //return System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings["AttachDir"], date.ToString("yyyyMMdd"));//文件目录
            return HttpContext.Current.Server.MapPath("UploadFiles") + "\\" + date.ToString("yyyyMMdd") + "\\";
        }

        #region 枚举
        /// <summary>
        /// 枚举转DataTable
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static DataTable EnumToDataTable(Type enumType)
        {
            //Type enumType = typeof(TEnum); // 获取类型对象
            FieldInfo[] enumFields = enumType.GetFields();    //获取字段信息对象集合

            DataTable table = new DataTable();
            table.Columns.Add("Name", Type.GetType("System.String"));
            table.Columns.Add("Value", Type.GetType("System.Int32"));
            //遍历集合
            foreach (FieldInfo field in enumFields)
            {
                if (!field.IsSpecialName)
                {
                    DataRow row = table.NewRow();
                    row[0] = field.Name;   // 获取字段文本值
                    row[1] = Convert.ToInt32(field.GetRawConstantValue());        // 获取int数值
                    //row[1] = (int)Enum.Parse(enumType, field.Name); 也可以这样

                    table.Rows.Add(row);
                }
            }
            return table;
        }


        #endregion

        #region Json解析转换
        /// <summary>
        /// 将datatable转换为json  
        /// </summary>
        /// <param name="dtb">Dt</param>
        /// <returns>JSON字符串</returns>
        public static string DataTableToJson(DataTable dtb)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            System.Collections.ArrayList dic = new System.Collections.ArrayList();
            foreach (DataRow dr in dtb.Rows)
            {
                System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
                foreach (DataColumn dc in dtb.Columns)
                {
                    drow.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                dic.Add(drow);

            }
            //序列化  
            return jss.Serialize(dic);
        }

        /// <summary>
        /// 解析json字符转换为对象、对象序列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)ser.ReadObject(ms);
            }
        }
        #endregion

        /// <summary>
        /// 获取控件值到数据对象属性
        /// </summary>
        /// <param name="dataObj">数据对象</param>
        /// <param name="propName">数据属性名</param>
        /// <param name="ctrlVal">控件值</param>
        public static void EvalControlValueToData(object dataObj, string propName, object ctrlVal)
        {
            PropertyInfo pi = dataObj.GetType().GetProperty(propName);
            Type t = pi.PropertyType;
            if ((t.IsGenericType) && (t.GetGenericTypeDefinition() == typeof(Nullable<>)))
                t = t.GetGenericArguments()[0];
            object nValue = null;
            if (ctrlVal != null)
            {
                if (ctrlVal.ToString().Length > 0)
                    nValue = Convert.ChangeType(ctrlVal, t);
            }
            pi.SetValue(dataObj, nValue, null);

        }

        public static object ChangeType(this object value, Type convertsionType)
        {
            //判断convertsionType类型是否为泛型，因为nullable是泛型类,
            if (convertsionType.IsGenericType &&
                //判断convertsionType是否为nullable泛型类
           convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null | value.ToString().Length == 0)
                {
                    return null;
                }

                //如果convertsionType为nullable类，声明一个NullableConverter类，该类提供从Nullable类到基础基元类型的转换
                NullableConverter nullableConverter = new NullableConverter(convertsionType);
                //将convertsionType转换为nullable对的基础基元类型
                convertsionType = nullableConverter.UnderlyingType;
            }
            return Convert.ChangeType(value, convertsionType);
        }

        /// <summary>
        /// 判断单元是否空
        /// </summary>
        /// <param name="cellValue"></param>
        /// <returns></returns>
        public static bool IsCellNull(object cellValue)
        {
            if (cellValue == null || cellValue == DBNull.Value)
                return true;
            return false;
        }
    }

    #region IEnumerable扩充
    /// <summary>     
    /// IEnumerable 擴充方法     
    /// </summary>     
    public static class IEnumerableExtensions
    {
        /// <summary>     
        /// 將 IEnumerable 轉換至 DataTable     
        /// </summary>     
        /// <param name="list">IEnumerable</param>     
        /// <returns>DataTable</returns>     
        public static DataTable ToDataTable(this IEnumerable list)
        {

            DataTable dt = new DataTable();
            PropertyInfo[] props = null;
            bool isCreatedColumn = false;
            foreach (object item in list)
            {
                ArrayList ary = new ArrayList();
                props = item.GetType().GetProperties();
                foreach (var pi in props)
                {
                    if (pi.Name.ToLower() != "extensiondata")
                    {
                        if (!isCreatedColumn)
                        {
                            DataColumn dc = new DataColumn();
                            dc.AllowDBNull = true;
                            dc.ColumnName = pi.Name;
                            Type colType = pi.PropertyType;
                            //if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                            //    colType = colType.GetGenericArguments()[0];
                            //dc.DataType = colType;
                            dt.Columns.Add(dc);
                        }
                        ary.Add(pi.GetValue(item, null));
                    }
                }

                object[] row = new object[ary.Count];
                ary.CopyTo(row);
                dt.Rows.Add(row);
                if (!isCreatedColumn)
                    isCreatedColumn = true;
            }
            return dt;
        }

        /// <summary>     
        /// 將 IEnumerable 轉換至 DataTable     
        /// </summary>     
        /// <param name="list">IEnumerable</param>     
        /// <returns>DataTable</returns>     
        public static DataTable ToDataTable(this IEnumerable list, Dictionary<object[], string> columns)
        {
            try
            {
                DataTable dt = new DataTable();
                PropertyInfo[] props = null;
                bool isCreatedColumn = false;
                foreach (object item in list)
                {
                    ArrayList ary = new ArrayList();
                    props = item.GetType().GetProperties();
                    foreach (var pi in props)
                    {
                        bool showColumn = columns.Count == 0 | columns.Any(p => p.Value == pi.Name);
                        if (showColumn & pi.Name.ToLower() != "extensiondata")
                        {
                            if (!isCreatedColumn)
                            {
                                DataColumn dc = new DataColumn();
                                dc.AllowDBNull = true;
                                dc.ColumnName = pi.Name;
                                Type colType = pi.PropertyType;
                                //if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                                //    colType = colType.GetGenericArguments()[0];
                                //dc.DataType = colType;
                                dt.Columns.Add(dc);
                            }
                            ary.Add(pi.GetValue(item, null));
                        }
                    }

                    foreach (var c in columns)
                    {
                        if (c.Key != null)
                        {
                            dt.Columns[c.Value].SetOrdinal(Convert.ToInt32(c.Key[0]));
                            dt.Columns[c.Value].Caption = c.Key[1].ToString();
                        }
                    }

                    object[] row = new object[ary.Count];
                    ary.CopyTo(row);
                    dt.Rows.Add(row);
                    if (!isCreatedColumn)
                        isCreatedColumn = true;
                }
                return dt;
            }
            catch { }
            return null;
        }

        public static DataTable ToDataTable<T>(this IList<T> data)
        { return ToDataTable<T>(data, null); }

        public static DataTable ToDataTable<T>(this IList<T> data, string[] exceptNames)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            int exceptCount = exceptNames == null ? 0 : exceptNames.Length;
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                if (exceptNames != null)
                    if (exceptNames.Contains(prop.Name))
                        continue;
                DataColumn dc = new DataColumn();
                dc.AllowDBNull = true;
                dc.ColumnName = prop.Name;
                Type colType = prop.PropertyType;
                table.Columns.Add(dc);
            }
            object[] values = new object[props.Count - exceptCount];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                { values[i] = props[i].GetValue(item); }
                table.Rows.Add(values);
            }
            return table;
        }

        /// <summary>
        /// 把包含子类对象的复合类对象序列转换为DataTable,以便加载数据到控件
        /// </summary>
        /// <typeparam name="T">包含的子类对象</typeparam>
        /// <param name="list">复合类对象序列</param>
        /// <param name="dt">控件定义好架构的DataTable</param>
        /// <returns>DataTable</returns>
        public static DataTable ConvertToDataTable<T>(this IEnumerable list, DataTable dt)
        {
            //DataTable dt = new DataTable();
            bool schemaIsBuild = false;
            PropertyInfo[] props = null;

            foreach (object item in list)
            {
                if (!schemaIsBuild)
                {
                    DataRow row = dt.NewRow();
                    props = item.GetType().GetProperties();
                    foreach (PropertyInfo pi in props)
                    {
                        if (pi.PropertyType == typeof(T))
                        {
                            PropertyInfo[] childProps = ((T)pi.GetValue(item, null)).GetType().GetProperties();
                            foreach (PropertyInfo p in childProps)
                            {
                                if (ExistsColumnName(dt.Columns, pi.Name))
                                    row[p.Name] = p.GetValue(pi, null);
                            }
                        }
                        else
                        {
                            if (ExistsColumnName(dt.Columns, pi.Name))
                                row[pi.Name] = pi.GetValue(item, null);
                        }
                    }

                    dt.Rows.Add(row);
                    schemaIsBuild = true;
                }
            }
            dt.AcceptChanges();
            return dt;
        }

        /// <summary>
        /// 把包含子类对象的复合类对象序列转换为DataTable,以便加载数据到控件
        /// </summary>
        /// <typeparam name="T">包含的子类对象</typeparam>
        /// <param name="list">复合类对象序列</param>
        /// <returns>DataTable</returns>
        public static DataTable ConvertToDataTable<T>(this IEnumerable list)
        {
            DataTable dt = new DataTable();
            //bool schemaIsBuild = false;
            PropertyInfo[] props = null;
            bool isCreatedColumn = false;

            //Array.ForEach<PropertyInfo>(list.get.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });

            foreach (object item in list)
            {
                //if (!schemaIsBuild)
                //{
                ArrayList ary = new ArrayList();
                //DataRow row = dt.NewRow();
                props = item.GetType().GetProperties();
                foreach (PropertyInfo pi in props)
                {
                    if (pi.PropertyType == typeof(T))
                    {
                        PropertyInfo[] childProps = ((T)pi.GetValue(item, null)).GetType().GetProperties();
                        foreach (PropertyInfo p in childProps)
                        {
                            if (p.Name.ToLower() != "extensiondata")
                            {
                                if (!isCreatedColumn)
                                {
                                    DataColumn dc = new DataColumn();
                                    dc.AllowDBNull = true;
                                    dc.ColumnName = p.Name;
                                    Type colType = p.PropertyType;
                                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                                        colType = colType.GetGenericArguments()[0];
                                    dc.DataType = colType;
                                    dt.Columns.Add(dc);
                                }
                                ary.Add(p.GetValue((T)pi.GetValue(item, null), null));
                                //dt.Columns.Add(new DataColumn(p.Name, p.PropertyType));
                                //row[p.Name] = p.GetValue(pi, null);
                            }
                        }
                    }
                    else
                    {
                        if (pi.Name.ToLower() != "extensiondata")
                        {
                            if (!isCreatedColumn)
                            {
                                DataColumn dc = new DataColumn();
                                dc.AllowDBNull = true;
                                dc.ColumnName = pi.Name;
                                Type colType = pi.PropertyType;
                                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                                    colType = colType.GetGenericArguments()[0];
                                dc.DataType = colType;
                                dt.Columns.Add(dc);
                            }


                            ary.Add(pi.GetValue(item, null));
                        }
                    }
                }
                object[] row = new object[ary.Count];
                ary.CopyTo(row);
                dt.Rows.Add(row);
                if (!isCreatedColumn)
                    isCreatedColumn = true;
                //schemaIsBuild = true;
                //}
            }
            dt.AcceptChanges();
            return dt;
        }

        private static bool ExistsColumnName(DataColumnCollection cols, string name)
        {
            foreach (DataColumn c in cols)
            {
                if (c.ColumnName.ToLower() == name.ToLower())
                    return true;
            }
            return false;
        }
    }
    #endregion

    #region OTConverter
    /// <summary>
    /// 对象转换类
    /// </summary>
    public static class OTConverter
    {
        /// <summary>   
        /// Convert a data table to an objct list   
        /// </summary>   
        /// <typeparam name="T"></typeparam>   
        /// <param name="t"></param>   
        /// <returns></returns>   
        public static List<T> ConvertTableToObject<T>(DataTable t) where T : new()
        {
            List<T> list = new List<T>();
            foreach (DataRow row in t.Rows)
            {
                T obj = ConvertToObject<T>(row);
                list.Add(obj);
            }

            return list;



        }

        /// <summary>   
        /// Convert an DataRow to an object   
        /// </summary>   
        /// <typeparam name="T"></typeparam>   
        /// <param name="row"></param>   
        /// <returns></returns>   
        public static T ConvertToObject<T>(DataRow row) where T : new()
        {
            object obj = new T();
            if (row != null)
            {
                DataTable t = row.Table;
                GetObject(t.Columns, row, obj);
            }
            if (obj != null && obj is T)
                return (T)obj;
            else
                return default(T);

        }

        private static void GetObject(DataColumnCollection cols, DataRow dr, Object obj)
        {
            Type t = obj.GetType(); //This is used to do the reflection   
            PropertyInfo[] props = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            //PropertyInfo[] props = t.GetProperties();
            foreach (PropertyInfo pro in props)
            {
                if (ExistsColumnName(cols, pro.Name))
                {
                    Type colType = pro.PropertyType;

                    pro.SetValue(obj,
                        dr[pro.Name] == DBNull.Value ? null : dr[pro.Name],
                        null);
                }
            }
        }

        private static bool ExistsColumnName(DataColumnCollection cols, string name)
        {
            foreach (DataColumn c in cols)
            {
                if (c.ColumnName.ToLower() == name.ToLower())
                    return true;
            }
            return false;
        }
    }
    #endregion
}
